﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using BusinessRule.DTO;
using MES.DataGateway.DBUtility;
using External.APICalling;
using System.Configuration;

namespace SendIndustrialNetwork
{
    public class APICommon
    {
        #region "增加属性"
        public uMESProcessResult SaveUserAttribute(List<ContainerStartInfo> paraList, Boolean isOtherConn)//add:Wangjh 20170925 增加参数是否选择外部服务器地址
        {
            uMESProcessResult result = new uMESProcessResult();
            String strInfo = "";
            Dictionary<String, List<ClientAPIEntity>> m_AttrList = new Dictionary<String, List<ClientAPIEntity>>();

            List<ClientAPIEntity> m_AttrChild = new List<ClientAPIEntity>();
            int i = 0;
            foreach (ContainerStartInfo para in paraList)
            {
                ClientAPIEntity attEntity = new ClientAPIEntity();

                attEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                attEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                attEntity.ClientDataName = "Name";
                attEntity.ClientDataValue = para.AttributeName;
                m_AttrChild.Add(attEntity);

                attEntity = new ClientAPIEntity();
                attEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                attEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                attEntity.ClientDataName = "DataType";
                attEntity.ClientDataValue = "4";
                m_AttrChild.Add(attEntity);

                attEntity = new ClientAPIEntity();
                attEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                attEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                attEntity.ClientDataName = "AttributeValue";
                attEntity.ClientDataValue = para.attributeValue;

                m_AttrChild.Add(attEntity);

                m_AttrList.Add(i.ToString(), m_AttrChild);
                i++;
            }

            List<ClientAPIEntity> m_DataList = new List<ClientAPIEntity>();

            ClientAPIEntity dataEntity = new ClientAPIEntity();

            String strSql = string.Format("SELECT c.containername,l.containerlevelname FROM CONTAINER c LEFT JOIN CONTAINERLEVEL l ON l.containerlevelid=c.levelid WHERE c.containername='{0}'", paraList[0].ContainerName);

            DataTable DT ;
            DT = isOtherConn ? OracleHelper.Query(strSql,true ).Tables[0] : OracleHelper.Query(strSql).Tables[0];//update:Wangjh 增加外部服务器连接判断

            dataEntity.ClientDataTypeEnum = DataTypeEnum.ContainerField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Container";
            dataEntity.ClientDataValue = paraList[0].ContainerName;
            dataEntity.ClientOtherValue = DT.Rows[0]["containerlevelname"].ToString().Trim();
            m_DataList.Add(dataEntity);

            CamstarClientAPI api;
            //if (isOtherConn)//add:Wangjh 20170925
            //{
            //    string[] tempStr=GetJXCamstarConn ().Split ('$');
            //    api = new CamstarClientAPI(tempStr[1].ToString(), tempStr[2].ToString(),
            //     tempStr[0].ToString().Split(':').First(), tempStr[0].ToString().Split(':').Last());
            //}
            //else {
                api = new CamstarClientAPI(ConfigurationManager.AppSettings["CamstarUserName"].ToString(),
                ConfigurationManager.AppSettings["CamstarPassword"].ToString());
            //}
           
            Boolean success = api.RunTxnServiceHasSubentity("ContainerAttrMaintDoc", "ContainerAttrMaint", m_DataList, "ServiceDetails", m_AttrList, ref  strInfo);
            result.Result = success;
            result.Message = "SaveUserAttribute"+strInfo;
            return result;
        }

        public uMESProcessResult SaveDenamicAttribute(List<ContainerStartInfo> paraList, Boolean isOtherConn)//add:Wangjh 20170925 增加参数是否选择外部服务器地址
        {

            uMESProcessResult result = new uMESProcessResult();
            String strInfo = "";

            Dictionary<String, List<ClientAPIEntity>> m_AttrList = new Dictionary<String, List<ClientAPIEntity>>();

            for (int i = 0; i < paraList.Count; i++)
            {
                List<ClientAPIEntity> m_AttrChild = new List<ClientAPIEntity>();

                ClientAPIEntity attEntity = new ClientAPIEntity();
                attEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                attEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                attEntity.ClientDataName = "Name";
                attEntity.ClientDataValue = paraList[i].AttributeName;
                m_AttrChild.Add(attEntity);

                attEntity = new ClientAPIEntity();
                attEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                attEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                attEntity.ClientDataName = "DataType";
                attEntity.ClientDataValue = "4";
                m_AttrChild.Add(attEntity);

                attEntity = new ClientAPIEntity();
                attEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                attEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                attEntity.ClientDataName = "AttributeValue";
                attEntity.ClientDataValue = paraList[i].attributeValue;
                m_AttrChild.Add(attEntity);

                m_AttrList.Add(i.ToString().Trim(), m_AttrChild);
            }

            List<ClientAPIEntity> m_DataList = new List<ClientAPIEntity>();

            ClientAPIEntity dataEntity = new ClientAPIEntity();

            dataEntity.ClientDataTypeEnum = DataTypeEnum.ContainerField;
            dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
            dataEntity.ClientDataName = "Container";
            dataEntity.ClientDataValue = paraList[0].ContainerName;
            dataEntity.ClientOtherValue = paraList[0].Level;
            m_DataList.Add(dataEntity);
            CamstarClientAPI api;
            //if (isOtherConn)
            //{
            //    string[] tempStr = GetJXCamstarConn().Split('$');
            //    api = new CamstarClientAPI(tempStr[1].ToString(), tempStr[2].ToString(),
            //     tempStr[0].ToString().Split(':').First(), tempStr[0].ToString().Split(':').Last());
            //}
            //else
            //{
                api = new CamstarClientAPI(ConfigurationManager.AppSettings["CamstarUserName"].ToString(),
                    ConfigurationManager.AppSettings["CamstarPassword"].ToString());
            //}
            Boolean success = api.RunTxnServiceHasSubentity("ContainerAttrMaintDoc", "ContainerAttrMaint", m_DataList, "ServiceDetails", m_AttrList, ref strInfo);
            result.Result = success;
            result.Message = "SaveDenamicAttribute" + strInfo;
            return result;
        }

        public uMESProcessResult SetUserAttribute(List<ContainerStartInfo> paraList, Boolean isOtherConn)//add:Wangjh 20170925 增加参数是否选择外部服务器地址
        {

            uMESProcessResult result = new uMESProcessResult();

            //'Dim strSql As String = String.Format("SELECT c.containerid,c.containername,t.userattributeid,t.attributevalue FROM userattribute  t " & vbCrLf & _
            //'                      "LEFT JOIN CONTAINER c ON c.containerid=t.parentid " & vbCrLf & _
            //'                      "WHERE t.userattributename='currSpecStatus'AND c.containername='{0}'", para.ContainerName)


            String strSql = String.Format("SELECT c.containerid,c.containername,t.userattributeid,t.attributevalue,t.userattributename FROM userattribute  t " +
                                  "LEFT JOIN CONTAINER c ON c.containerid=t.parentid " +
                                  "WHERE  c.containername='{0}'", paraList[0].ContainerName);
            

            DataTable DT ;
            DT = isOtherConn ? OracleHelper.Query(strSql, true).Tables[0] : OracleHelper.Query(strSql).Tables[0];//add:Wangjh 20170925 增加参数是否选择外部服务器地址

            if (DT.Rows.Count == 0)
                result = isOtherConn ? SaveUserAttribute(paraList, true) : SaveUserAttribute(paraList, false);//update:Wangjh 20170925 
            else
            {
                List<ContainerStartInfo> attList = new List<ContainerStartInfo>();
                ContainerStartInfo tmpEnity = new ContainerStartInfo();
                foreach (ContainerStartInfo para in paraList)
                {
                    String strFilter = String.Format("userattributename='{0}'", para.AttributeName);
                    DataRow[] tmpRow = DT.Select(strFilter);
                    if (tmpRow.Length == 0)
                    {
                        tmpEnity = new ContainerStartInfo();
                        tmpEnity.AttributeName = para.AttributeName;
                        tmpEnity.attributeValue = para.attributeValue;
                        tmpEnity.ContainerName = para.ContainerName;
                        tmpEnity.Level = para.Level;
                        attList.Add(tmpEnity);
                    }
                    else
                    {
                       string strUSql = String.Format("UPDATE userattribute t SET t.attributevalue='{0}' WHERE t.userattributeid='{1}'", para.attributeValue, tmpRow[0]["userattributeid"].ToString().Trim());
                       if (isOtherConn) OracleHelper.ExecuteSql(strUSql, true);//update:Wangjh 20170925
                       else OracleHelper.ExecuteSql(strUSql);
                        result.Result = true;
                    }
                }
                if (attList.Count > 0)
                {
                    DT = OracleHelper.Query(strSql).Tables[0];
                    foreach (DataRow row in DT.Rows)
                    {
                        tmpEnity = new ContainerStartInfo();
                        tmpEnity.AttributeName = row["userattributename"].ToString().Trim();
                        tmpEnity.attributeValue = row["attributevalue"].ToString().Trim();
                        tmpEnity.ContainerName = paraList[0].ContainerName;
                        tmpEnity.Level = paraList[0].Level;
                        attList.Add(tmpEnity);
                    }
                    uMESProcessResult result1;
                    result1 = isOtherConn ? SaveDenamicAttribute(attList, true) : SaveDenamicAttribute(attList, false);
                    result.Result = result1.Result;
                    if (!result1.Result)
                        result.Message = result1.Message;
                }
            }
            return result;
        }
        #endregion


        #region 机匣测试服务器连接add:Wangjh 20170925
        /// <summary>
        /// 获取测试机匣服务器Camstar连接地址
        /// </summary>
        /// <returns></returns>
        private string GetJXCamstarConn() {
            return ConfigurationManager.AppSettings["JXServerHost"].ToString();
        }
        #endregion
    }
}